package cky_parser;

import java.util.*;
import java.io.*;

public class Grammar 
{
	ArrayList<String[]> Rules;
	ArrayList<String[]> Dict;
	
	
	public Grammar(String ruleFile, String dictFile)
	{
		Rules = new ArrayList<String[]>();
		Dict = new ArrayList<String[]>();
		loadFile(ruleFile, Rules);
		loadFile(dictFile, Dict);
	}
	
	public void loadFile (String fileName, ArrayList<String[]> Rules)
	{
		try
		{
			FileInputStream f = new FileInputStream(fileName);
			int ch = 0;
			String currentWord ="";
			ArrayList<String> rule = new ArrayList<String>();
			while ((ch = f.read()) != -1)
			{
				if (ch == '\n')								//New line
				{
					if (rule.size() > 0)
					{
						rule.add(currentWord);
						String[] tempValue = new String[rule.size()];
						rule.toArray(tempValue);
						Rules.add(tempValue);
					}
					currentWord = "";
					rule = new ArrayList<String>();
				}
				else
				{
					if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))		//Valid character
					{
						currentWord += (char)ch;
					}
					else
					{
						if (currentWord != "")
						{
							rule.add(currentWord);
							currentWord = "";
						}
					}
				}
			}
			
			f.close();
		}
		catch (IOException e)
		{
			
		}
	}
	
	public String checkGrammar (String[] rule)
	{
		for (int i = 0; i< Rules.size(); i++)
		{
			if (Rules.get(i)[1].compareTo(rule[0]) == 0 && Rules.get(i)[2].compareTo(rule[1]) == 0)
				return Rules.get(i)[0];
		}
		return "";
	}
	
	public ArrayList<String> checkDictionary (String word)
	{
		ArrayList<String> found = new ArrayList<String>();
		
		for (int i = 0; i< Dict.size(); i++)
		{
			if (Dict.get(i)[1].compareTo(word) == 0)
				found.add(Dict.get(i)[0]);
		}
		
		return found;
	}
}





